package com.net.xpay.web.controller.merchant;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.web.vo.ChargeRecordSearchVo;
import com.net.xpay.web.vo.ChargeRecordVo;
import com.net.common.model.ResultData;
import com.net.common.model.ResultList;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.enums.invoice.OpenInvoiceStatus;
import com.net.xpay.core.constant.PayMethod;
import com.net.xpay.core.domain.AccountLog;
import com.net.xpay.core.domain.ChargeRecord;
import com.net.xpay.core.enums.AccountBillType;
import com.net.xpay.core.enums.PayStatus;
import com.net.xpay.core.manager.AccountLogManager;
import com.net.xpay.core.manager.ChargeRecordManager;
import com.net.xpay.core.model.ChargeModel;
import com.net.xpay.core.model.ChargeRecordSearchModel;
import com.net.xpay.core.service.ChargeService;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2020/5/12 16:11

 */
@RestController
@Slf4j
@RequestMapping("/merchant/charge-record")
@Api(tags = "商户/充值", description = "商户 充值 net")
public class ChargeRecordController {

    @Autowired
    private ChargeService chargeService;

    @Autowired
    private ChargeRecordManager chargeRecordManager;

    @Autowired
    private AccountLogManager accountLogManager;

    /**
     * 发起充值
     */
    @ApiOperation("发起充值")
    @PostMapping("/do-charge")
    public ResultData<String> doCharge(@ApiIgnore @RequestUser User merchant, @RequestBody ChargeModel chargeModel) {
        ChargeRecord record = chargeService.doCharge(merchant, chargeModel);
        if (chargeModel.getPayMethod() == null || PayMethod.PC.equals(chargeModel.getPayMethod())) {
            return new ResultData<>(record.getLastPayUrl());
        } else {
            return new ResultData<>(record.getMobilePayQrCode());
        }
    }

    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<ChargeRecordSearchVo> search(@ApiIgnore @RequestUser User merchant, @RequestBody ChargeRecordSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());
        List<ChargeRecord> chargeRecords = chargeRecordManager.search(searchModel);
        List<ChargeRecordSearchVo> vos = BeanCopierUtil.batchCopy(ChargeRecord.class, ChargeRecordSearchVo.class, chargeRecords);
        for (ChargeRecordSearchVo vo : vos) {
            AccountLog accountLog = accountLogManager.findByRelatedId(vo.getUserId(), AccountBillType.CHARGE, vo.getId());
            if (accountLog == null) {
                continue;
            }
            vo.setBeforeAmount(accountLog.getBeforeAmount());
            vo.setAfterAmount(accountLog.getAfterAmount());
        }
        long count = chargeRecordManager.searchCount(searchModel);

        return new ResultPagedList<>(vos, count, searchModel);
    }

    /**
     * 查询待开票的充值成功的记录
     */
    @ApiOperation("查询待开票的充值成功的记录")
    @PostMapping("/list-wait-invoice-charge-record")
    public ResultList<ChargeRecordVo> getWaitInvoiceChargeRecord(@ApiIgnore @RequestUser User merchant) {
        ChargeRecordSearchModel searchModel = new ChargeRecordSearchModel();
        searchModel.setUserId(merchant.getId());
        searchModel.setOpenInvoiceStatus(OpenInvoiceStatus.WAIT);
        searchModel.setPayStatus(PayStatus.PAYED);
        searchModel.setCreateMinTime(LocalDateTime.now().minusYears(1));
        List<ChargeRecord> list = chargeRecordManager.list(searchModel);
        List<ChargeRecordVo> vos = BeanCopierUtil.batchCopy(ChargeRecord.class, ChargeRecordVo.class, list);
        return new ResultList<>(vos);
    }

    /**
     * 获取最近充值成功的记录
     */
    @ApiOperation("获取最近充值成功的记录")
    @GetMapping("/get-last-paid-charge-record")
    public ResultData<ChargeRecord> getLastPaidChargeRecord(@ApiIgnore @RequestUser User merchant) {
        ChargeRecord chargeRecord = chargeRecordManager.findLastPaid(merchant.getId());

        return new ResultData<>(chargeRecord);
    }


    /**
     * 统计可开票金额
     */
    @ApiOperation("统计可开票金额")
    @GetMapping("/stat-wait-invoicing-amount")
    public ResultData<Long> statWaitInvoicingAmount(@ApiIgnore @RequestUser User merchant) {
       LocalDateTime startTime = LocalDateTime.now().minusYears(1);
       Long amount = chargeRecordManager.statWaitInvoicingAmount(merchant.getId(),startTime);;

        return new ResultData<>(amount);
    }

    /**
     * 充值明细导出
     */
    @ApiOperation("充值明细导出")
    @GetMapping("/export")
    public ResultData<Boolean> exportAccountLog(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);
        ChargeRecordSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, ChargeRecordSearchModel.class);
        searchModel.setUserId(merchant.getId());
        List<ChargeRecord> chargeRecordsList = chargeRecordManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();

        model.put("records", chargeRecordsList);

        String fileName = "充值明细.xlsx";
        String template = "/excel/tpl/充值明细.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }
}
